<?php

/**
 * Created by PhpStorm.
 * User: 何婷婷
 * Date: 2017/3/20
 * Time: 21:24
 */
namespace User\Controller;

use PhpOffice\PhpWord\PhpWord;
use Tsy\Plugs\Excel\Excel;
use User\Object\UserObject;
use Zend\Stdlib\Hydrator\NamingStrategy\MapNamingStrategy;


class IndexController
{
    public $db;
    public $values;


    /**
     * IndexController constructor.
     */
    public function __construct()
    {
        /*$this->db = M('date');
        $this->values = new IndexController();*/
    }

    public function index()
    {
//        $i = 0;
        $doc = new \Document();
        $doc->loadPDM('./Doc/User.pdm');
//        $doc->generateControllers()->generateModels()->generateObjects();
//        $doc->autoFinishControllerByObject(new UserObject());
        $doc->getDoc()->renderMD('doc.md');

        // $doc->getDoc('doc.md')->renderDOC('doc.doc');
        // $word=new PHPWord();
    }

    public function phpWord()
    {
        $phpword = new PhpWord();
        $section = $phpword->addSection();

        $excel = new Excel();
        $date = $excel->read('./Doc/order.xlsx');
        $dateOne = array_map_format([
            '序号' => '序号',
            '日期' => '日期',
            '部门' => '部门',
            '订车人' => '订车人',
            '联系电话' => '联系电话',
            '用车路线' => '用车路线',
            '时间' => '时间',
            '里程' => '里程',
            '结算金额' => '结算金额',
            '车型' => '车型',
            '司机' => '司机',
            '垫付应收' => '垫付应收',
            '驾驶员劳务费' => '驾驶员劳务费',
            '垫付应付' => '垫付应付',
            '备注' => '备注',
            '用车事宜' => '用车事宜',
        ], array_values($date)[0]);
        $dateTwo = json_decode(str_replace('null', 0, json_encode($dateOne)), true);
        $Departments = array_column($dateTwo, '部门');
        $People = array_column($dateTwo, '订车人');
        $phone = array_column($dateTwo, '联系电话');
        $Date = array_column($dateTwo, '日期');
        $number = array_column($dateTwo, '序号');
        $Cars = array_column($dateTwo, '车型');
        $Drivers = array_column($dateTwo, '司机');
        $mile = array_column($dateTwo, '里程');
        $Time = array_column($dateTwo, '时间');
        $line = array_column($dateTwo, '用车路线');

        $text[0] = array_column($dateTwo, '部门');
        $text[1] = array_column($dateTwo, '订车人');
        $text1 = '';
        $text2 = '';
        for ($i = 0; $i < count($text[0]); $i++) {
            $text1 .= "[$i]" . ":" . $text[0][$i];
            $text2 .= "[$i]" . ":" . $text[1][$i];
        }

        $departmentB = '';//部门
        $date = '';//日期
        $peopleT = ''; //订车人
        $telT = ''; //电话
        $lineT = '';//用车路线
        $timeT = ''; //时间
        $mileT = '';  //里程


        foreach ($Date as $key => $value) {
            if ($value == 0) {
                continue;
            }
            $values = rtrim($value, '0');
            $keys = substr($key, 0, 6);
            $date .= "[$keys] : " . $values . "  ";
        };

        foreach ($Departments as $key => $value) {
            if ($value == '') {
                continue;
            }
            $departmentB .= "[$key] : " . $value . "  ";
        }

        foreach ($People as $key => $value) {
            if ($value == '') {
                continue;
            }
            $peopleT .= "[$key] : " . $value . "  ";
        }

        foreach ($phone as $key => $value) {
            if ($value == '') {
                continue;
            }
            $telT .= "[$key] : " . $value . "  ";
        }

        foreach ($Time as $key => $value) {
            if ($value == '') {
                continue;
            }
            $timeT .= "[$key] : " . $value . "  ";
        }

        $fontStyleNameTitle = 'TitleStyle';
        $phpword->addFontStyle(
            $fontStyleNameTitle,
            array('name' => 'title', 'size' => 16, 'color' => '1B2232', 'bold' => true));
        $section->addText('                                Orders.xlsx 文档', $fontStyleNameTitle);

        $fontStyleNameH1 = new \PhpOffice\PhpWord\Style\Font();
        $fontStyleNameH1->setBold(true);
        $fontStyleNameH1->setName('h1');
        $fontStyleNameH1->setSize(14);
        $H1Content = $section->addText('序号 ： （1）长途 （2）短途', array('name' => 'h1'));
        $H1Content->setFontStyle($fontStyleNameH1);

        $h2Content = $section->addText('', array('name' => 'h2'));
        $h2Content->setFontStyle($fontStyleNameH1);

        $fontStyleNameH1->setName('h2');
        $fontStyleNameH1->setSize('12');
        $h2Content = $section->addText('日期：' . $date, array('name' => 'h2'));
        $h2Content->setFontStyle($fontStyleNameH1);

        $h2Content = $section->addText('', array('name' => 'h2'));
        $h2Content->setFontStyle($fontStyleNameH1);

        $h3Content = $section->addText('部门：' . $departmentB, array('name' => 'h2'));
        $h3Content->setFontStyle($fontStyleNameH1);

        $h2Content = $section->addText('', array('name' => 'h2'));
        $h2Content->setFontStyle($fontStyleNameH1);

        $h2Content = $section->addText('订车人' . $peopleT, array('name' => 'h2'));
        $h2Content->setFontStyle($fontStyleNameH1);

        $h2Content = $section->addText('', array('name' => 'h2'));
        $h2Content->setFontStyle($fontStyleNameH1);

        $h2Content = $section->addText('联系电话' . $telT, array('name' => 'h2'));
        $h2Content->setFontStyle($fontStyleNameH1);

        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpword, 'Word2007');
        $objWriter->save('Word.docx');

    }

    public function Word()
    {
        $phpword = new PhpWord();
        $section = $phpword->addSection();

        $fontStyleNameTitle = 'TitleStyle';
        $phpword->addFontStyle(
            $fontStyleNameTitle,
            array('name' => 'title', 'size' => 16, 'color' => '1B2232', 'bold' => true));
        $section->addText('                                         标题', $fontStyleNameTitle);
        $section->addText('', array('name' => 'h2'));

        $fontStyleNameH1 = new \PhpOffice\PhpWord\Style\Font();
        $fontStyleNameH1->setBold(true);
        $fontStyleNameH1->setName('h1');
        $fontStyleNameH1->setSize(14);
        $fontStyleNameH1->setColor('#000000');
        $H1Content = $section->addText('标题一 要点（黑体，加粗，小四号）', array('name' => 'h1', 'color' => '000000 '));
        $H1Content->setFontStyle($fontStyleNameH1);

        $section->addText('', array('name' => 'h2'));

        $fontStyleNameH2 = 'H2Style';
        $phpword->addFontStyle(
            $fontStyleNameH2,
            array('name' => 'H2Style', 'size' => 10, 'color' => '443f3f', 'bold' => true));
        $section->addText('    正文一 （四号，宋体，1.5倍行距，段首缩进2个字符）', $fontStyleNameH2);

        $section->addText('', array('name' => 'h2'));

        $H1Content = $section->addText('标题二 要点（黑体，加粗，小四号）', array('name' => 'h1'));
        $H1Content->setFontStyle($fontStyleNameH1);

        $section->addText('', array('name' => 'h2'));

        $fontStyleNameH3 = 'H3Style';
        $phpword->addFontStyle(
            $fontStyleNameH3,
            array('name' => 'title', 'size' => 10, 'color' => '443f3f', 'bold' => true));
        $section->addText('    正文二 （四号，宋体，1.5倍行距，段首缩进2个字符）', $fontStyleNameH3);

        $section->addText('', array('name' => 'h2'));

        $H1Content = $section->addText('标题三', array('name' => 'h1'));
        $H1Content->setFontStyle($fontStyleNameH1);

        $section->addText('', array('name' => 'h2'));

        $fontStyleNameH4 = 'H3Style';
        $phpword->addFontStyle(
            $fontStyleNameH4,
            array('name' => 'title', 'size' => 10, 'color' => '443f3f', 'bold' => true));
        $section->addText('     自定义要点1：宋体，五号字，段首加项目符号，内容是否加粗根据实际情况决定。', $fontStyleNameH4);
        $section->addText('', array('name' => 'h2'));

        $fontStyleNameH4 = 'H3Style';
        $phpword->addFontStyle(
            $fontStyleNameH4,
            array('name' => 'title', 'size' => 10, 'color' => '443f3f', 'bold' => true));
        $section->addText('     自定义要点2：自定义要点段间距为段前6磅或0.5行，段后6磅或0.5行。', $fontStyleNameH4);

        $section->addText('', array('name' => 'h2'));
        $H1Content = $section->addText('一级标题', array('name' => 'h1'));
        $H1Content->setFontStyle($fontStyleNameH1);

        $section->addText('', array('name' => 'h2'));
        $fontStyleNameH2 = 'H2Style';
        $phpword->addFontStyle(
            $fontStyleNameH2,
            array('name' => 'H2Style', 'size' => 12, 'color' => '1B2232', 'bold' => true));
        $section->addText('   二级标题', $fontStyleNameH2);


        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpword, 'Word2007');
        $objWriter->save('1.docx');

    }


    public function threadCrawler()
    {
        $detailUrl = M('task');
        $values = [];
        $r = iconv('gbk', 'utf-8', file_get_contents('http://data.eastmoney.com/DataCenter_V3/gdhs/GetList.ashx?reportdate=&market=&changerate==&range==&pagesize=100&page=1&sortRule=-1&sortType=NoticeDate&js=var%20YoNVdQFV&param=&rt=49675151'));
        $data = json_decode(strstr($r, "{"), true);
        for ($i = 0; $i < count($data['data']); $i++) {
            foreach ($data['data'][$i] as $key => $value) {
                $values[0][$key][$i] = $value;
            }
        }
        if ($values) {
            $i = 0;
            foreach ($values[0]['SecurityCode'] as $value) {
                $codeDetail[$i] = $value;
                $u[$i] = "http://data.eastmoney.com/DataCenter_V3/gdhs/GetDetial.ashx?code=$codeDetail[$i]&js=var%20SSWXVzBq&pagesize=50&page=1&sortRule=-1&sortType=EndDate&param=&rt=49675378";

                //获取到的url对应存入数据库
                $url['urlId'] = $codeDetail[$i];
                $url['detailUrl'] = $u[$i];
                if ($detailUrl->where(['urlId' => $codeDetail[$i]])->find()) {
                    continue;
                } else {
                    $add = $detailUrl->add($url);
                }

                if (empty($u)) {
                    $url['statues'] = 0;//未获取到地址，进程为开始
                } elseif ($add) {
                    $url['statues'] = 1;//存数据库成功
                } else {
                    $url['statues'] = 2;//存数据库失败
                }
                $detailUrl->add($url['statues']);
                $i++;
            }
        }

        //读数据库url
        $ReadUrlDetail = [];
        $codeDetail=[];//对应代码code
        for ($i = 0; $i < count($values[0]['SecurityCode']); $i++) {
            $codeDetail[$i] = $values[0]['SecurityCode'][$i];
            $ReadUrl[$i] = $detailUrl->where(['urlId' => $codeDetail[$i]])->find();//读取从数据库存的url
            $ReadUrlDetail[$i] = $ReadUrl[$i]['detailUrl'];
        }
         $this->multiCurl($ReadUrlDetail);//curl并发操作,返回详情列表

        $readText=$this->readText($codeDetail);

        $db = $this->db($values);
        if ($db) {
            echo 'success';
        } else {
            echo 'fail';
        }
    }
    //读取文件里面的数据
    public function readText($id)
    {
        $data=fopen("detail.txt",'r');
        if ($data){
            $i=0;
        while(!feof($data)){  //一个json对应一个详情列表，每次读取一个json
            $read=fgets($data);
            $readText=json_decode($read,true);
            $this->detailDB($readText['data'],$id[$i]);//将数据插入数据库
            $i++;
            }
        }
        fclose($data);
        return $this;
    }

    //curl并发获取数据并存入文件
    public function multiCurl($log)
    {
        $conn = [];
        $res = [];
        $string = '';
        $mh = curl_multi_init();

        foreach ($log as $i => $url) {
            $conn[$i] = curl_init($url);
            curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
            curl_multi_add_handle($mh, $conn[$i]);//向curl批处理会话中添加单独的curl句柄
        }
        do {
            $status = curl_multi_exec($mh, $active);
            $info = curl_multi_info_read($mh);
            /*  if (false !== $info) {
                  var_dump($info);
              }*/
        } while ($status === CURLM_CALL_MULTI_PERFORM || $active);

        foreach ($log as $i => $url) {
            $res[$i] = curl_multi_getcontent($conn[$i]);
            $str = strstr($res[$i], "{");
            $string .= $str . "\r\n";
            curl_close($res[$i]);
        }
        curl_multi_remove_handle($mh, $info['handle']);
        curl_close($mh['handle']);

        return file_put_contents('detail.txt', iconv('GBK', 'utf-8', $string));
    }

    //主页数据数据库操作
    public function db($values)
    {
        $db = M('crawler');
        for ($i = 0; $i < count($values[0]['SecurityCode']); $i++) {
            $Dbdate['SecurityCode'] = $values[0]['SecurityCode'][$i];
            $Dbdate['SecurityName'] = $values[0]['SecurityName'][$i];
            $Dbdate['LatestPrice'] = $values[0]['LatestPrice'][$i];
            $Dbdate['PriceChangeRate'] = $values[0]['PriceChangeRate'][$i];
            $Dbdate['HolderNum'] = $values[0]['HolderNum'][$i];
            $Dbdate['PreviousHolderNum'] = $values[0]['PreviousHolderNum'][$i];
            $Dbdate['HolderNumChange'] = $values[0]['HolderNumChange'][$i];
            $Dbdate['HolderNumChangeRate'] = $values[0]['HolderNumChangeRate'][$i];
            $Dbdate['RangeChangeRate'] = $values[0]['RangeChangeRate'][$i];
            $Dbdate['EndDate'] = $values[0]['EndDate'][$i];
            $Dbdate['PreviousEndDate'] = $values[0]['PreviousEndDate'][$i];
            $Dbdate['HolderAvgCapitalisation'] = $values[0]['HolderAvgCapitalisation'][$i];
            $Dbdate['HolderAvgStockQuantity'] = $values[0]['HolderAvgStockQuantity'][$i];
            $Dbdate['TotalCapitalisation'] = $values[0]['TotalCapitalisation'][$i];
            $Dbdate['CapitalStock'] = $values[0]['CapitalStock'][$i];
            $Dbdate['NoticeDate'] = $values[0]['NoticeDate'][$i];
            $t = $db->add($Dbdate);
            if (!$t) {
                die;
            }
        }
        return true;
    }

    //详情页数据数据库操作
    public function detailDB($values,$id)
    {
        $detail=M('detail');
        $detailDb['DetailGroupUID']=$id;//DetailGroup
        for ($i=0;$i<count($values);$i++){
               $detailDb['HolderNum']=$values[$i]['HolderNum'];
                $detailDb['PreviousHolderNum']=$values[$i]['PreviousHolderNum'];
                $detailDb['HolderNumChange']=$values[$i]['HolderNumChange'];
                $detailDb['HolderNumChangeRate']=$values[$i]['HolderNumChangeRate'];
                $detailDb['RangeChangeRate']=$values[$i]['RangeChangeRate'];
                $detailDb['EndDate']=$values[$i]['EndDate'];
                $detailDb['HolderAvgCapitalisation']=$values[$i]['HolderAvgCapitalisation'];
                $detailDb['HolderAvgStockQuantity']=$values[$i]['HolderAvgStockQuantity'];
                $detailDb['TotalCapitalisation']=$values[$i]['TotalCapitalisation'];
                $detailDb['CapitalStock']=$values[$i]['CapitalStock'];
                $detailDb['NoticeDate']=$values[$i]['NoticeDate'];
                $detailDb['CapitalStockChange']=$values[$i]['CapitalStockChange'];
                $detailDb['CapitalStockChangeEvent']=$values[$i]['CapitalStockChangeEvent'];
                $detailDb['ClosePrice']=$values[$i]['ClosePrice'];

                if ($detail->where(['HolderNum' =>$values[$i]['HolderNum'],['PreviousHolderNum'=>$values[$i]['PreviousHolderNum']]])->find()) {
                    continue;
                }else{
                    if (!$detail->add($detailDb)){
                        file_put_contents('E:\projects\User\detailDb.txt', date('Y-m-d H:i:s').' ' ."Error: 数据插入失败"."\r\n", FILE_APPEND);
                    }
                }
            }

            //return true;
        }

    /*public function crawler()
    {
        file_put_contents('E:\projects\User\crawler.txt', date('Y-m-d H:i:s') . "\r\n", FILE_APPEND);
        $values = [];
        $detailDate = [];
        $url = $this->getUrl(0);
        $cache_key = md5($url);
        //如果缓存里面有数据，读取缓存里面的数据
        if (!($result = cache($cache_key))) {
            $r = iconv('gbk', 'utf-8', file_get_contents($url));
            $write = cache($cache_key, $r, 86400);//有效期一天
            if ($write) {
                $result = cache($cache_key);
            }
        } else {
            $result = cache($cache_key);
        }
        $data = json_decode(strstr($result, "{"), true);
        for ($i = 0; $i < count($data['data']); $i++) {
            foreach ($data['data'][$i] as $key => $value) {
                $values[0][$key][$i] = $value;
            }
        }
        //获取详情
        if ($values) {
            $i = 0;
            foreach ($values[0]['SecurityCode'] as $value) {
                $codeDetail[$i] = $value;
                $detailUrl = M('detailUrl');
                $url['detailUrl'] = $codeDetail[$i];
                $detailUrl->add($url);
                $detailT = iconv('GBK', 'utf-8', file_get_contents($this->getUrl($codeDetail[$i])));
                $detailDate = json_decode(strstr($detailT, "{"), true);
                $i++;
            }
        }
        if (!empty($detailDate)) {
            for ($i = 0; $i < count($detailDate['data']); $i++) {
                foreach ($detailDate['data'][$i] as $key => $value) {
                    $values[1][$key][$i] = $value;
                }
            }
        }

        return $values;
    }*/
}